<?php

namespace app\service;

//玩家宠物服务层
use app\enum\PetCode;
use app\model\Pet;
use app\model\RedeemCode;
use app\model\User;
use app\model\UserPet;
use app\model\UserPetRedeem;
use app\model\UserProp;

class UserPetService extends Base
{

    public function list($user_id)
    {
        $user_pet = UserPet::where('user_id', $user_id)->find();
        return apiSuccess($user_pet);
    }

    public function add(User $user, $code, $force)
    {

        $redeem = RedeemCode::where('code', $code)->find();
        if (!$redeem) {
            return apiError('兑换码不存在');
        }
        if ($redeem->status == PetCode::STATUS['已使用']) {
            return apiError('兑换码已被使用');
        }

        $pet = Pet::where('id', $redeem->pet_id)->find();

        $user_pet = new UserPet();
        $user_pet->user_id = $user->id;
        $user_pet->cn_name = $pet->cn_name;
        $user_pet->pet_id = $redeem->pet_id;
        $user_pet->power = $pet->power;
        $user_pet->mood = $pet->mood;
        $user_pet->birthday = date('m/d', time());
        $user_pet->duration = 0;
        $user_pet->save();

        //更新用户宠物兑换记录
        UserPetRedeem::create([
            'user_id' => $user->id,
            'pet_id' => $redeem->pet_id,
            'redeem_code_id' => $redeem->id,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        //更新兑换码状态
        $redeem->status = PetCode::STATUS['已使用'];
        $redeem->save();

        if ($force) {
            $user->pet_id = $pet->id;
            $user->save();
        }

        return apiSuccess($user_pet);
    }

    //设置昵称 和 对我的称呼
    public function set_nickname($user_id, $user_pet_id, $nickname, $call_name)
    {
        $user_pet = UserPet::where('user_id', $user_id)->where('id', $user_pet_id)->find();
        if (!$user_pet) {
            return apiError('宠物不存在');
        }
        $user_pet->cn_name = $nickname;
        $user_pet->call_name = $call_name;
        $user_pet->save();
        return apiSuccess($user_pet);
    }

    //喂养宠物
    public function feed($user_id, $user_pet_id, $user_prop_id, $num)
    {

        //获取宠物信息
        $user_pet = UserPet::where('user_id', $user_id)->where('id', $user_pet_id)->find();
        if (!$user_pet) {
            return apiError('宠物不存在');
        }
        //获取食物信息
        $user_prop = UserProp::where('id', $user_prop_id)->find();
        if (!$user_prop) {
            return apiError('物品不存在');
        }
        if ($user_prop->num < $num) {
            return apiError('物品数量不足');
        }
        //喂养 增加宠物亲密度
        $user_pet->exp += $num * $user_prop->exp;

        $user_pet->save();

        //更新物品数量
        $user_prop->num -= $num;
        $user_prop->save();


        return apiSuccess($user_pet);
    }

    //记录宠物事件
    public function record_event($user_id, $user_pet_id, $event_type, $event_desc)
    {

        return apiSuccess();
    }



}